package com.bnzj.cloud.oauth2resource.custom;

import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import com.bnzj.core.util.JsonUtils;
import com.bnzj.core.web.constant.CommonWebEnum;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName CustomOauth2AuthenticationEntryPoint
 * @Description Bearer token 校验异常处理类
 * @Author
 * @Date 2020/3/2
 * @Version V1.0
 **/

public class CustomOauth2AuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult<?> responseResult ;
        if(authException instanceof OAuth2AuthenticationException){
            responseResult = new ResponseResult<>(new ResultCode(CommonWebEnum.TOKEN_INVALID.getCode(), CommonWebEnum.TOKEN_INVALID.getMsg()));
        }else {
            responseResult = new ResponseResult<>(new ResultCode(CommonWebEnum.ACCESS_DENIED.getCode(), CommonWebEnum.ACCESS_DENIED.getMsg()));
        }
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.getWriter().write(JsonUtils.objToJson(responseResult));
    }
}
